<?php

namespace haibao\weixin\data;

class WeixinInfo extends \haibao\weixin\data\BaseMysql{
	public function __construct() {
		parent::__construct ( '\haibao\weixin\model\data\weixininfo' );
	}
	
	public function getWeixinName(){
	    $sql = 'select Id,AccountName from WeixinInfo';
	    $result = $this->query($sql);
	    $weiXinInfo = array();
	    while($row = $result->fetch_assoc()){
	        $weiXinInfo[$row['Id']] = $row['AccountName'];
	    }
        return $weiXinInfo;
	}
	
	public function getWeixinPlatformTokenCache($accountId){
		$cache = new \haibao\weixin\cache\WeixinInfo();
		
		return $cache->getWeixinPlatformTokenCache($accountId);
	}
	
	public function setWeixinPlatformTokenCache($accountId,$token,$expires = 7100){
		$cache = new \haibao\weixin\cache\WeixinInfo();
		
		$cache->setWeixinPlatformTokenCache($accountId, $token, $expires);
	}
	
	public function getWeixinJsTicketCache(){
		$cache = new \haibao\weixin\cache\WeixinInfo();
		return $cache->getWeixinJsTicketCache();
	}
	
	public function setWeixinJsTicketCache($value,$expires = 7200){
		$cache = new \haibao\weixin\cache\WeixinInfo();
		$cache->setWeixinJsTicketCache($value, $expires);
	}
	
	public function delWeixinPlatformTokenCache($accountId){
		$cache = new \haibao\weixin\cache\WeixinInfo();
	
		$cache->delWeixinPlatformTokenCache($accountId);
	}
	
	public function getWinxinList(){
        $sql = "SELECT a.*, ( SELECT UserCount FROM WeixinSummary AS b WHERE a.Id = b.WeixinInfoId ORDER BY b.Id DESC LIMIT 1 ) AS recordCount
                FROM WeixinInfo AS a ORDER BY  a.Id DESC";
	    $result = $this->query($sql);
	    $weixinList = array();
	    while ($row = $result->fetch_assoc()){
	        $weixinList[$row['Id']] = $row;
	    }
	    return $weixinList;
	}
	
	public function getWeixinMenuListById($id,$isMainMenu = false,$Status){
	    $sql = "SELECT * FROM WeixinMenu WHERE WeixinInfoId = %s";
	    if ($isMainMenu){
	        $sql .=" AND ParentId = 0";
	    }else{
	        $sql .=" AND ParentId != 0";
	    }
	    if($Status){
	        $sql .=" AND Status = 1";
	    }
	    $sql .=" ORDER BY OrderNo";
	    $result = $this->query($sql,array($id));
	    $weixinMenuList = array();
	    while ($row = $result->fetch_assoc()){
	        $weixinMenuList[$row['Id']] = $row;
	    }
	    return $weixinMenuList;
	}
	
	public function isHaveSameWeixinMenuName($id,$name,$weixinInfoId){
	    $sql = 'SELECT * FROM WeixinMenu';
	    if($name){
	        $sql .= " WHERE `Name` = %s AND WeixinInfoId = %s AND Status = %s";
	    }
	    if($id){
	        $sql .= " AND Id != ".$id;
	    }
	    $result = $this->query($sql,array($name,$weixinInfoId,\haibao\weixin\model\data\WeixinMenu::STATUS_ENABLE));
	    $data = array();
	    while ($row = $result->fetch_assoc()){
	        $data = $row;
	    }
	    return $data;
	}
	
    public function isExistSubMenu($id){
        $sql = "select count(*) as childNum from `WeixinMenu` where ParentId=%s and Status=%s";
        $channelInfo = $this->query($sql,array($id,\haibao\weixin\model\data\WeixinMenu::STATUS_ENABLE))->fetch_assoc();
        return !empty($channelInfo['childNum']) ? true : false;
    }
    
    /**
     * 通过AppUserKey得微信缓存信息
     * @param string $userKey
     * @return \haibao\weixin\model\data\WeixinInfo
     */
    public function getInfoByAppUserKey($userKey){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    	$weixinInfoModel = $cache->getWeixinInfo($userKey);
    	if(empty($weixinInfoModel)){
    		$weixinInfoModel = new \haibao\weixin\model\data\WeixinInfo();
    		$result = $this->query('select * from WeixinInfo where AppUserKey=%s',array($userKey));
    		while($result->fetch_assoc()){
    			$weixinInfoModel->Id = $result->getData('Id');
    			$weixinInfoModel->Token = $result->getData('Token');
    			$weixinInfoModel->AppId = $result->getData('AppId');
    			$weixinInfoModel->AppSecret = $result->getData('AppSecret');
    			$weixinInfoModel->WelcomeMsg = $result->getData('WelcomeMsg');
    			$weixinInfoModel->PublicMsg = $result->getData('PublicMsg');
    			$weixinInfoModel->ImageTextMsg = $result->getData('ImageTextMsg');
    		}
    		
    		$cache->setWeixinInfo($userKey, json_encode($weixinInfoModel->toArray(), true));
    	} else {
    		$weixinInfoModel = json_decode($weixinInfoModel);
    	}
    	
    	return $weixinInfoModel;
    }
    
    /**
     * 通过微信ID得当前所有有效的关键词
     * @param int $infoId
     */
    public function getInfoKeywordsById($infoId){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    	$weixinKeywords = $cache->getWeixinKeywords($infoId);
    	if(empty($weixinKeywords)){
    		$weixinKeywords = array();
    		$sql = 'select Name,ReplyType,ReplyContent,KeywordType from WeixinKeywords where WeixinInfoId=%s and Status=%s and StartTime<=%s and EndTime>=%s';
    		$result = $this->query($sql,array($infoId,\haibao\weixin\model\data\WeixinKeywords::STATUS_ENABLE,date("Y-m-d"),date("Y-m-d")));
    		while($result->fetch_assoc()){
    			$weixinKeywords[] = array('keyWords'=>json_decode($result->getData('Name')),'ReplyContent'=>json_decode($result->getData('ReplyContent'),true),'ReplyType'=>$result->getData('ReplyType'),'KeywordType'=>$result->getData('KeywordType'));
    		}
    		$cache->setWeixinKeywords($infoId, json_encode($weixinKeywords, true));
    	} else {
    		$weixinKeywords = json_decode($weixinKeywords,true);
    	}
    	
    	return $weixinKeywords;
    }
    
    public function getWeixinKeywordsAndMenuByWeixinId($id,$type){
        switch ($type){
            case 'Keywords':
                $sql=" SELECT * FROM WeixinKeywords WHERE WeixinInfoId = %s AND `Status` = 1";
                break;
            case 'Menu':
                $sql="SELECT * FROM WeixinMenu WHERE WeixinInfoId = %s AND `Status` = 1";
                break;
        }
        $result = $this->query($sql,array($id,1));
        $data = array();
        while ($row = $result->fetch_assoc()){
            $data[$row['Id']] = $row;
        }
        return $data;
    }
    
    public function saveLastOperateHistory($key,$content){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    
    	$cache->saveLastOperateHistory($key, $content);
    }
    
    public function getWeixinOperateHistory($key){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    
    	return $cache->getWeixinOperateHistory($key);
    }
    
    public function clearWeixinOperateHistory($key){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    	
    	$cache->clearWeixinOperateHistory($key);
    }
    
    public static function getAuthUserInfoFromOpenId($openId){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    	 
    	return $cache->getAuthUserInfoFromOpenId($openId);
    }
    
    public static function setAuthUserInfo($openId,$userInfo){
    	$cache = new \haibao\weixin\cache\WeixinInfo();
    	 
    	return $cache->setAuthUserInfo($openId,$userInfo);
    }
}
